<template>
  <el-row class="login-container" justify="center" align="middle">
    <el-card>
      <template #header>
        <div class="card-header">
          <img src="../../../public/login-head.png" alt="" />
        </div>
      </template>
      <div class="jump-link">
        <el-link type="primary" @click="handleChange">{{
          formType ? '返回登录' : '注册账号'
        }}</el-link>
      </div>
      <el-form :model="loginForm" :rules="rules" ref="loginFormRef">
        <el-form-item prop="userName">
          <el-input
            v-model="loginForm.userName"
            placeholder="手机号"
            prefix-icon="UserFilled"
          ></el-input>
        </el-form-item>
        <el-form-item prop="passWord">
          <el-input
            v-model="loginForm.passWord"
            type="password"
            placeholder="密码"
            prefix-icon="Lock"
          ></el-input>
        </el-form-item>
        <el-form-item v-if="formType" prop="validCode">
          <el-input
            v-model="loginForm.validCode"
            placeholder="验证码"
            prefix-icon="Lock"
            ><template #append>
              <span @click="countdownChange">{{ countdown.validText }}</span>
            </template></el-input
          >
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            :style="{ width: '100%' }"
            @click="submitForm(loginFormRef)"
            >{{ formType ? '注册账号' : '登录' }}</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
  </el-row>
</template>

<script setup>
import { reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
import { getCode, getUser, login } from '../../api/index';

// 表单数据
const loginForm = reactive({
  userName: '15521114361',
  passWord: '704387661',
  validCode: '',
});

// 表单校验
const rules = reactive({
  userName: [
    { required: true, trigger: 'blur', message: '必须输入手机号' },
    {
      pattern: /^1[3-9][0-9]{9}$/,
      message: '请输入正确的手机号',
      trigger: 'blur',
    },
  ],
  passWord: [
    { required: true, trigger: 'blur', message: '必须输入密码 ' },
    { min: 6, max: 12, message: '请输入正确的密码', trigger: 'blur' },
  ],
});

// 创建router实例
const router = useRouter();

const loginFormRef = ref();
// 点击按钮
const submitForm = async (loginFormRef) => {
  console.log(loginFormRef);
  console.log(formType.value);
  if (!loginFormRef) return;
  await loginFormRef.validate((valid, fields) => {
    console.log(222);
    if (valid) {
      // 注册页面
      if (formType.value) {
        getUser(loginForm).then(({ data }) => {
          if (data.code === 10000) {
            ElMessage.success('注册成功，请登录');
            formType.value = false;
          }
        });
      } else {
        // 登录页面
        console.log(333);
        login(loginForm).then(({ data }) => {
          console.log(111);
          if (data.code === 10000) {
            ElMessage.success('登录成功');
            console.log(data);
            //  将用户信息存起来
            localStorage.setItem('pz_token', data.data.token);
            localStorage.setItem(
              'pz_userInfo',
              JSON.stringify(data.data.userInfo)
            );
            router.push('/');
          }
        });
      }
    } else {
      // console.log('error submit!', fields);
    }
  });
};

// 发送短信
const countdown = reactive({
  validText: '获取验证码',
  time: 60,
});

const formType = ref(false);

const handleChange = () => {
  formType.value = !formType.value;
};

//定义验证码倒计时函数
let flag = false;
const countdownChange = () => {
  // 如果已发送 存在计时器不处理
  if (flag) return;

  // 判断手机号是否正确
  let phoneReg =
    /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/;
  if (!loginForm.userName || !phoneReg.test(loginForm.userName)) {
    return ElMessage({
      message: '请检查手机号是否正确',
      type: 'warning',
    });
  }

  // 如果第一次点 则倒计时
  const time = setInterval(() => {
    if (countdown.time <= 0) {
      countdown.time = 60;
      countdown.validText = '获取验证码';
      flag = false;
      clearInterval(time);
    } else {
      countdown.time -= 1;
      countdown.validText = `剩余${countdown.time}s`;
    }
  }, 1000);
  flag = true;
  getCode({ tel: loginForm.userName }).then(({ data }) => {
    console.log('data', data);
    if (data.code === 10000) {
      ElMessage.success('发送成功');
    }
  });
};
</script>

<style lang="less" scoped>
:deep(.el-card__header) {
  padding: 0;
}
.login-container {
  height: 100%;
  background-image: url('../../../public/1.jpg');
  background-repeat: no-repeat;
  background-size: cover;
  .card-header {
    background-color: #899fe1;
    img {
      width: 430px;
    }
  }
  .jump-link {
    text-align: right;
    margin-bottom: 10px;
  }
}
</style>
